import React, { Component, Fragment } from 'react'
import {
  Upload,
  Form,
  Input,
  Button,
  Table,
  message,
  Popconfirm,
  Select
} from 'antd'
import {
  UploadOutlined,
  CloseCircleOutlined,
  RedoOutlined
} from '@ant-design/icons'
import styles from './index.module.scss'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import { actionCreators } from '../../../store/index'
import { SearchOutlined } from '@ant-design/icons'
import httpUtil from 'utils/request'
import { SERVER } from 'config'

const { Option } = Select;

class UserList extends Component {
  constructor(props) {
    super(props)

    this.state = {
      //复选框数据
      selectedRowKeys: [],
      //搜索关键词
      keyword: '',
      // 分类搜索选项
      option: "userId",
      //
      status: 0,
      pageNumber: 1,
      pageSize: 9,
      //   limit: 10,
      total: '',
      //totalOne加载总数时的标志位，设置为1，
      totalOne: 1,
      csvfile: [],
      csvfileList: 11,
      adminId: [],
      data: [],
      listData: [],
      timer: '',
      //表头
      columns: [
        {
          title: '用户ID',
          dataIndex: 'userId',
          key: 'userId'
        },
        {
          title: '用户名',
          dataIndex: 'userName',
          key: 'userName'
        },
        {
          title: '密码',
          dataIndex: 'password',
          key: 'password'
        },
        {
          title: '专业',
          dataIndex: 'major',
          key: 'major'
        },
        {
          title: '班级',
          dataIndex: 'sclass',
          key: 'sclass'
        },
        {
          title: '学号',
          dataIndex: 'sid',
          key: 'sid'
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          key: 'email'
        },
        {
          title: '电话',
          dataIndex: 'tel',
          key: 'tel'
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          width: 270,
          render: (text, record, index) => {
            return (
              <div className={styles['inline-button']}>
                {/* <Button type="primary">编辑</Button> */}
                <Popconfirm
                  title="确认删除该用户吗？"
                  onConfirm={this.confirmDelete.bind(this, record.userId)}
                  onCancel={this.cancelDelete}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button
                    danger
                    icon={<CloseCircleOutlined />}
                  >
                    删除
                  </Button>
                </Popconfirm>
                <Button
                  icon={<RedoOutlined />}
                  onClick={() => this.onResetPassword(record.userId)}>
                  重置密码
                </Button>
              </div>
            )
          }
        }
      ]
    }
  }

  confirmDelete = (userId) => {
    this.onDelete(userId)
  }

  cancelDelete = (e) => {
    console.log(e);
    message.error('Click on No');
  }

  confirmDeleteSome = () => {
    this.onDeleteSome()
  }

  cancelDeleteSome = (e) => {
    console.log(e);
    message.error('Click on No');
  }

  selectHandleChange = (value) => {
    console.log(`selected ${value}`);
  }

  //传统导入文件方法
  //   //csv文件导入
  //   onImportstu = () => {
  //     httpUtil.getTeacherList().then((res) => {
  //       const adminId = res.data[0].adminId
  //       var data = document.getElementById('file').files[0]
  //       console.log(data)
  //       var formdata = new FormData()
  //       //可以通过append()方法来追加数据
  //       formdata.append('csvfile', data)
  //       formdata.append('columns', this.state.csvfileList)
  //       formdata.append('adminId', adminId)
  //       httpUtil
  //         .importstu(formdata)
  //         .then((res) => {
  //           if (res.message === '失败') {
  //             message.warning('导入失败，请不要传入重复数据')
  //           }
  //           if (res.message === '成功') {
  //             message.success('导入成功')
  //           }
  //         }, this.loadData())
  //         .catch((err) => console.log(err))
  //     })
  //   }

  //暂时只能删除没有开始比赛的用户
  onDelete = userId => {
    httpUtil
      .deletestu({ userId })
      .then(res => {
        if (res.message === '成功') {
          message.success(userId + ' 删除成功')
        } else {
          message.error(res.data + userId + ' 正在比赛')
        }
      }, this.loadData())
      .catch(err => console.log(err))
  }

  //批量删除暂时只能删除没有开始比赛的用户
  onDeleteSome = () => {
    const userIds = this.state.selectedRowKeys.join()
    if (userIds) {
      httpUtil
        .deletestus({ userIds })
        .then(res => {
          if (res.message === '成功') {
            message.success('批量删除成功')
          } else {
            message.error('有用户正在比赛，批量删除失败！')
          }
        }, this.loadData())
        .catch(err => console.log(err))
    } else {
      const key = 'updatable'
      setTimeout(() => {
        message.warning({
          content: '请选择需要删除的用户',
          key,
          duration: 2
        })
      }, 200)
      return false
    }
  }

  //重置密码
  onResetPassword = userId => {
    var formdata = new FormData()
    //可以通过append()方法来追加数据
    formdata.append('status', this.state.status)
    formdata.append('userId', userId)
    httpUtil
      .resetPassword(formdata)
      .then(res => {
        message.success('用户' + userId + '，重置密码为123456')
      }, this.loadData())
      .catch(err => console.log(err))
  }

  //搜索
  onFinish = value => {
    console.log(value);
    const { keyword, option } = value
    if (keyword === undefined || keyword === '') {
      message.info('请输入内容查找')
      return false
    }
    const { data } = this.state
    const reg = new RegExp(`${keyword}`, 'g')
    let listData = []
    data.forEach((data, index) => {
      if (data[option] && data[option].search(reg) !== -1) {
        console.log(data);
        listData.push(data)
      }
    })
    if (listData.length === 0) {
      message.info(`内容: ${keyword}，没有找到`)
      this.setState({
        listData: listData,
        total: listData.data
      })
    } else {
      message.info(`内容: ${keyword}，找到了${listData.length}条相关数据`)
      this.setState({
        listData: listData,
        total: listData.data
      })
    }
  }
  componentDidMount() {
    this.loadData()
  }
  //搜索
  serachAll = input => {
    const keyword = input.target.value

    if (keyword === undefined || keyword === '') {
      this.setState({ listData: this.state.data })
    }
    const { data } = this.state
    const reg = new RegExp(`${keyword}`, 'g')
    let listData = []
    data.forEach((data, index) => {
      for (let item in data) {
        if (data[item] !== null) {
          if (data[item].search(reg) !== -1 && item !== "password") {
            listData.push(data)
            break
          }
        }
      }
    })
    if (listData.length === 0) {
      this.setState({
        listData: listData,
        total: listData.data
      })
    } else {
      this.setState({
        listData: listData,
        total: listData.data
      })
    }
  }

  //获取列表数据
  loadData = () => {
    httpUtil
      .findAllApprovedUser()
      .then(res => {
        const data = res.data
        this.setState({
          data: data,
          listData: data,
          total: data.length
        })
      })
  }

  //复选框
  onCheckebox = selectedRowKeys => {
    this.setState({ selectedRowKeys })
  }

  downloadManual = () => {
    const eleLink = document.createElement('a');
    eleLink.style.display = 'none';
    eleLink.target = "_blank"

    eleLink.href = `${SERVER}/erpn/help/help.docx`;
    document.body.appendChild(eleLink);
    eleLink.click();
    document.body.removeChild(eleLink);
  }

  downloadTemplate = () => {
    const eleLink = document.createElement('a');
    eleLink.style.display = 'none';
    eleLink.target = "_blank"

    eleLink.href = `${SERVER}/erpn/help/template.csv`;
    document.body.appendChild(eleLink);
    eleLink.click();
    document.body.removeChild(eleLink);
  }

  render() {
    const _this = this
    const props = {
      name: 'file',
      action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
      headers: {
        authorization: 'authorization-text'
      },
      onChange(info) {
        if (info.file.status === 'done') {
          // httpUtil.getTeacherList().then(res => {
          //   const adminId = res.data[0].adminId
          const adminId = 'wangyong' //获取教师信息接口有问题，写的假数据，todo

          var formdata = new FormData()
          //可以通过append()方法来追加数据
          formdata.append('csvfile', info.file.originFileObj)
          formdata.append('columns', _this.state.csvfileList)
          formdata.append('adminId', adminId)
          httpUtil
            .importstu(formdata)
            .then(res => {
              if (res.message === '失败') {
                message.error(
                  `${info.file.name} 文件导入失败，请不要传入重复数据`
                )
              }
              if (res.message === '成功') {
                message.success(`${info.file.name} 文件导入成功！`)
              }
            }, _this.loadData())
            .catch(err => console.log(err))
          // })
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} file upload failed.`)
        }
      }
    }
    const { columns, listData } = this.state
    const rowSelection = {
      onChange: this.onCheckebox
    }
    return (
      <Fragment>
        <div className='search-box'>
          <Form layout='inline' onFinish={this.onFinish.bind(this)}>
            <Form.Item name='keyword'>
              <Input
                placeholder='请输入内容'
                ref={ref => {
                  this.searchUserRef = ref
                }}
                onChange={this.serachAll}
              />
            </Form.Item>
            <Form.Item shouldUpdate={true} name="option" initialValue="userId">
              <Select defaultValue="userId" style={{ width: 120 }} onChange={this.selectHandleChange}>
                <Option value="userId">用户ID</Option>
                <Option value="userName">用户名</Option>
                <Option value="major">专业</Option>
                <Option value="sclass">班级</Option>
                <Option value="sid">学号</Option>
                <Option value="email">邮箱</Option>
                <Option value="tel">电话</Option>
              </Select>
            </Form.Item>
            <Form.Item shouldUpdate={true}>
              <Button
                type='primary'
                htmlType='submit'
                icon={<SearchOutlined />}>
                综合搜索
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className='content-box'>
          <Table
            pagination={{
              total: this.state.total,
              pageSizeOptions: [9, 40, 70, 100],
              defaultPageSize: 9
            }}
            className='table-wrap'
            rowSelection={rowSelection}
            size='small'
            rowKey='userId'
            columns={columns}
            dataSource={listData}
            bordered
          />
          <div className={[styles["footer-btns"]]}>
            <Popconfirm
              title="确认批量删除用户吗？"
              onConfirm={this.confirmDeleteSome.bind(this)}
              onCancel={this.cancelDelete}
              okText="确认"
              cancelText="取消"
            >
              <Button
                danger
                className={styles['pull-left']}
                icon={<CloseCircleOutlined />}>
                批量删除
              </Button>
            </Popconfirm>
            <Button className={styles['pull-left']} onClick={this.downloadManual}>下载说明书</Button>
            <Button className={styles['pull-left']} onClick={this.downloadTemplate}>下载模板</Button>
            <Upload {...props}>
              <Button icon={<UploadOutlined />}>批量导入</Button>
            </Upload>

          </div>
          {/* 传统导入文件方法
              <Button className="pull-left" onClick={() => this.onImportstu()}>
                批量导入
              </Button>
              <input
                className="pull-left"
                type="file"
                id="file"
                accept=".csv"
                allowClear
              /> */}
        </div>
      </Fragment>
    )
  }
}
const mapStateToProps = state => ({
  common: state.common
})

const mapDispatchToProps = {
  findAllApprovedUser: actionCreators.findAllApprovedUser
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(UserList))
